package io.xccit.train.filter;

import io.xccit.train.common.util.JwtUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * @author CH_ywx
 * @version 1.0
 * @create 2024/11/10
 * <p>会员登录拦截器</p>
 */
@Component
public class MemberLoginFilter implements Ordered, GlobalFilter {

    @Autowired
    private JwtUtil jwtUtil;

    private static final Logger LOG = LoggerFactory.getLogger(MemberLoginFilter.class);

    /**
     * 拦截器
     * @param exchange 路由请求
     * @param chain 过滤器链
     * @return 拦截结果
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        String path = exchange.getRequest().getURI().getPath();
        LOG.info("请求路径:{}", path);
        //排除不需要拦截的请求
        if (path.contains("/member/member/login")
                || path.contains("/member/member/registry")
                || path.contains("/member/member/logout")
                || path.contains("/member/member/sendCode")
            ){
            return chain.filter(exchange);
        }
        //获取token
        String token = exchange.getRequest().getHeaders().getFirst("token");
        //token是否为空
        if (token==null || token.isEmpty()){
            LOG.info("请求路径:{}被拦截,原因:token为空", path);
            ServerHttpResponse response = exchange.getResponse();
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
        //校验token
        boolean isToken = jwtUtil.verify(token);
        if (!isToken){
            LOG.info("请求路径:{}被拦截,原因:token已过期", path);
            ServerHttpResponse response = exchange.getResponse();
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
        return chain.filter(exchange);
    }

    /**
     * 优先级
     * @return 优先级顺序 值越小优先级越高
     */
    @Override
    public int getOrder() {
        return 0;
    }
}
